<template>
  <div style="background-color: #FFFFFF;padding: 15px">
    <span style="font-size: 19px;font-weight: 600">志愿活动列表</span><br><br>

    <div  style="display: flex; ">
      <div class="type-name">所属类目：</div>
      <div class="card-container">
        <a-tabs  type="card" class="tabs" @change="changeCategory(state.courseLabel)"
                 v-model:activeKey="state.courseLabel"
                 style="width: 358px;margin-left: 10px"
                :tabBarStyle="{ margin: '0px',borderBottom: 'unset' }"  :tab-position="'top'">
          <a-tab-pane key="">
            <template v-slot:tab>
              <div>全部</div>
            </template>
          </a-tab-pane>
          <a-tab-pane key="报名中">
            <template v-slot:tab>
              <div>报名中</div>
            </template>
          </a-tab-pane>
          <a-tab-pane key="进行中">
            <template v-slot:tab>
              <div>进行中</div>
            </template>
          </a-tab-pane>
          <a-tab-pane key="已结束">
            <template v-slot:tab>
              <div>已结束</div>
            </template>
          </a-tab-pane>
          <a-tab-pane key="未通过">
            <template v-slot:tab>
              <div>未通过</div>
            </template>
          </a-tab-pane>
        </a-tabs><br>
      </div>
    </div>

    <a-form layout='inline'>
      <a-form-item name="userAccount">
        <div class="course-name">关键字：</div>
        <a-input :style="{ width: '200px' }" placeholder="请输入关键字查询" v-model:value="keyWord"/>
      </a-form-item>
      <a-form-item name="startTime">
        <div class="course-name">开始：</div>
        <a-date-picker v-model:value="startTimeForm" />
      </a-form-item>
      <a-form-item name="endTime">
        <div class="course-name">结束：</div>
        <a-date-picker v-model:value="endTimeForm" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="searchByInput" style="margin-left:15px">
          <search-outlined />
          查询
        </a-button>
        <a-button @click="refresh" style="margin-left:15px">
          <redo-outlined />
          重置
        </a-button>

        <a-button type="primary" @click="state.isAdd = true" style="margin-left:15px">
          <plus-circle-outlined />
          发布活动
        </a-button>

      </a-form-item>
    </a-form>
    <div style="height: 20px;"></div>
  </div>

  <div class="workContent">
    <a-spin :spinning="state.mySpinning">
      <a-table :columns="columns" :data-source="activityList" bordered :pagination="false">
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex == 'eventImgUrl'">
            <a-image :preview="false" style="width: 65px;height: 65px;" :src="text"></a-image>
          </template>

          <template v-if="column.dataIndex == 'status'">
            <span v-if="text == '已通过'" style="color: green">{{text}}</span>
            <span v-if="text == '未通过'" style="color: blueviolet">{{text}}</span>
            <span v-if="text == '报名中'" style="color: purple">{{text}}</span>
            <span v-if="text == '已结束'" style="color: orange">{{text}}</span>
            <span v-if="text == '审核中'" style="color: red">{{text}}</span>
          </template>

          <template  v-if="column.dataIndex === 'operation'">
            <a style="margin-right: 10px" @click = "startModal(record)">审核</a>
            <a-popconfirm
                title="确认删除吗?"
                cancelText="取消"
                okText="确认"
                placement="topLeft"
                @confirm="deleteA(record.eventId)"
            >
              <template #icon><question-circle-outlined style="color: red" /></template>
              <a style="color: red;margin-left: 10px">删除</a>
            </a-popconfirm>
          </template>
        </template>
      </a-table>

      <div style="width: 100%;height: 55px">
        <a-pagination style="float: right;margin-top: 10px" v-model:current="state.current"
                      @change="changeNum(state.current)"
                      :total="state.total" show-less-items />
      </div>

    </a-spin>
  </div>

  <a-modal v-model:visible="state.isAudit" :title="newAudit.title" @ok="handleOk" :width="700"
           cancelText="取消"  ok-text="确认"
  >
    <a-image :preview="false" style="width: 65px;height: 65px;" :src="newAudit.eventImgUrl"></a-image>
    <a-descriptions size="size" :column="2" style="margin-top: 10px">
      <a-descriptions-item label="承办人">{{newAudit.userName}}</a-descriptions-item>
      <a-descriptions-item label="活动地点">{{ newAudit.location }}</a-descriptions-item>
      <a-descriptions-item label="开始时间">{{ newAudit.startTime }}</a-descriptions-item>
      <a-descriptions-item label="结束时间">{{newAudit.endTime}}</a-descriptions-item>
      <a-descriptions-item label="活动人数">{{ newAudit.maxNum }}</a-descriptions-item>
      <a-descriptions-item label="活动标签">{{ newAudit.tags }}</a-descriptions-item>
      <a-descriptions-item label="活动描述">{{ newAudit.description }}</a-descriptions-item><br>
      <a-descriptions-item label="活动状态"><a-cascader v-model:value="state.statusValue" :options="options" /></a-descriptions-item>
    </a-descriptions><br>
  </a-modal>

  <a-modal v-model:visible="state.isAdd" title="发布活动" :destroyOnClose="true"
           :footer="null" @cancel="cancelActivity">
    <a-form
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
    >
      <a-form-item name="upload" label="上传头像" >
        <div style="margin-top: -5px">
          <input class="input_image left" id="file" type="file" @change="change" accept="image/*" />
          <img class="show_input_image left" v-if="addObj.img != ''" :src="addObj.img" />
          <img class="show_input_image left" v-if="addObj.img ==''" src="/img/addAva.png" />
        </div>
      </a-form-item>

      <a-form-item
          label="活动名称" v-bind="validateInfos.title"
      >
        <a-input v-model:value="addObj.title" />
      </a-form-item>

      <a-form-item
          label="活动地点"
          v-bind="validateInfos.location"
      >
        <a-input v-model:value="addObj.location" />
      </a-form-item>

      <a-form-item
          label="最大人数"
          v-bind="validateInfos.maxNum"
      >
        <a-input-number id="inputNumber" v-model:value="addObj.maxNum" :min="1" :max="1000" />
      </a-form-item>

      <a-form-item
          label="活动得分"
          v-bind="validateInfos.grade"
      >
        <a-input-number id="inputNumber" v-model:value="addObj.grade" :min="1" :max="10" />
      </a-form-item>

      <a-form-item
          label="活动描述"
      >
        <a-textarea v-model:value="addObj.description" placeholder="请输入活动描述" allow-clear />
      </a-form-item>

      <a-form-item
          label="开始时间"
      >
        <a-date-picker show-time placeholder="Select Time"  @change="onStartOk"/>
      </a-form-item>

      <a-form-item
          label="结束时间"
      >
        <a-date-picker show-time placeholder="Select Time" @change="onEndOk"/>
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 6, span: 16 }">
        <a-button type="dashed" @click="resetFields">重置</a-button>&nbsp;&nbsp;&nbsp;&nbsp;
        <a-button type="primary" @click.prevent="addActivity">确认</a-button>
      </a-form-item>

    </a-form>
  </a-modal>

</template>

<script setup>
import {reactive, ref} from "vue";
import {Form, message} from "ant-design-vue";
import {addActivityApi, deleteAApi, getActivityList, updateActivity} from "@/utils/activity";
import dayjs from "dayjs";
import axios from "axios";
import {useStore} from "vuex";
const useForm = Form.useForm;

const state = reactive({
  mySpinning: false,     //是否加载
  current: 1,            //分页第几页
  courseLabel: '',       //状态
  total: undefined,
  formatStart: '',     //转化后的开始时间
  formatEnd: '',       //转化后的结束时间
  isAudit: false,      //模态框
  statusValue: [],     //状态
  isAdd: false,
  startObj: {},     //开始时间对象
  endObj: {},       //结束时间对象
})

const activityList = ref([])

const keyWord = ref('')
const startTimeForm = ref()
const endTimeForm = ref()

const options = [
  {
    value: '已通过',
    label: '已通过',
  },
  {
    value: '未通过',
    label: '未通过',
  },
  {
    value: '进行中',
    label: '进行中',
  },
  {
    value: '报名中',
    label: '报名中',
  },
  {
    value: '已结束',
    label: '已结束',
  },
]

const columns = [
  {
    title: '活动头像',
    dataIndex: 'eventImgUrl',
    key: 'eventImgUrl',
    width: 92,
  },
  {
    title: 'ID',
    dataIndex: 'eventId',
    key: 'eventId',
    width: 55,
  },
  {
    title: '活动名称',
    dataIndex: 'title',
    key: 'title',
    width: 120,
  },
  {
    title: '承办人',
    dataIndex: 'userName',
    key: 'userName',
    width: 100,
  },
  {
    title: '活动描述',
    dataIndex: 'description',
    key: 'description',
    width: 220,

  },
  {
    title: '活动地点',
    dataIndex: 'location',
    key: 'location',
    width: 90
  },
  {
    title: '活动状态',
    dataIndex: 'status',
    key: 'status',
    width: 90,
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: 158,
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    width: 158,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: 110,
  }
]

//格式化时间
function formatDate(time){
  let nyr = time.slice(0, 10)
  let sfm = time.slice(11,19)

  let newTime = nyr + ' ' + sfm

  return newTime;
}

//获取课程列表
function getActivity(current,pageSize,keyWord,startTime,endTime,courseLabel){
  state.mySpinning = true
  console.log(current,pageSize,keyWord,startTime,endTime,courseLabel)
  getActivityList(current,pageSize,keyWord,startTime,endTime,courseLabel).then(res => {
    if (res.data.code == 0){
      console.log(res.data.data.records)
      state.mySpinning = false
      activityList.value = res.data.data.records
      state.total = res.data.data.total
      activityList.value.forEach(e => {
        e.startTime = formatDate(e.startTime)
        e.endTime = formatDate(e.endTime)
      })
    }else{
      state.mySpinning =false
      console.log(res)
    }
  })
}

const addObj = reactive({
  img: '',
  title: '',
  location: '',
  maxNum: 1,
  grade: 1,
  description: '',
  tags: '0',
  addStartTime: '',
  addEndTime: '',
})

const rulesRef = reactive({
  title: [{
    required: true,
    message: '请输入活动名称',
  }],
  location: [{
    required: true,
    message: '请输入活动地点',
  }],
  maxNum: [{
    required: true,
    message: '请输入最大人数',
  }],
  grade: [{
    required: true,
    message: '请选择活动分数',
  }],

});

const onStartOk = (value, dateString) =>{
  state.startObj = value
  addObj.addStartTime = dateString
}

const onEndOk = (value, dateString) =>{
  state.endObj = value
  addObj.addEndTime = dateString
}

const deleteA = function (id){
  console.log(id)
  deleteAApi(id).then(res => {
    if (res.status == 200){
      message.success('删除成功')
      getActivity(1,10,'','','','')
    }

  })
}

const {
  resetFields,
  validate,
  validateInfos,
} = useForm(addObj, rulesRef, {
  onValidate: (...args) => console.log(),
});
const store = useStore()

const cancelActivity = function (){
  resetFields()
  addObj.addStartTime = ''
  addObj.addEndTime = ''
}

const addActivity = function (){

  if (new Date(addObj.addStartTime) < new Date(addObj.addEndTime) && new Date(addObj.addStartTime) > new Date()){
    validate().then(()=>{
      let event = {
        title: addObj.title,
        description: addObj.description,
        endTime: addObj.addEndTime,
        eventImgUrl: addObj.img,
        eventScore: addObj.grade,
        location: addObj.location,
        maxNum: addObj.maxNum,
        startTime: addObj.addStartTime,
        tags: addObj.tags,
        delFlag: 0,
        status: '审核中',
        userId: store.state.id
      }
      addActivityApi(event).then(res =>{
        if (res.data.code == 0){
          message.success('新增成功')
          getActivity(1,10,'','','','')
        }else{
          message.error('新增失败')
        }
        state.isAdd = false
        resetFields()
      })
    })
  }else {
    message.error('时间格式错误')
  }

}



const change = function (e){
  let imgInput = document.getElementById('file')

  if (!imgInput.value){
    message.error('没有选择图片')
  }

  let file = imgInput.files[0];
  let size = file.size;
  if (size >= 1 * 1024 * 1024) {
    message.error('文件大小超出限制')
    return false;
  }
  if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
    message.error('不是有效的图片')
    return;
  }
  let formData = new FormData()
  formData.append('file',file)

  axios.post('http://121.37.0.16:8080/api/file/upload',formData,{
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    if (res.data.code == 0){
      addObj.img = 'http://121.37.0.16:9000/public/'+ res.data.data.fileName[0]
    }
  })
}


getActivity(1,10,'','','','')

//查询
const searchByInput = function (){

  if (startTimeForm.value == undefined && endTimeForm.value == undefined){
    getActivity(1,10,keyWord.value,'','',state.courseLabel)
  }else{
    state.formatStart = startTimeForm.value == undefined? '' : dayjs(startTimeForm.value).format('YYYY-MM-DD')
    let myEndTime = endTimeForm.value == undefined ? '': dayjs(endTimeForm.value).format('YYYY-MM-DD')
    let a = new Date(myEndTime)
    a = a.setDate(a.getDate() + 1 )
    let b = new Date(a).toLocaleString()
    state.formatEnd = timestampToTime(b)
    getActivity(1,10,keyWord.value,state.formatStart,state.formatEnd,state.courseLabel)
  }
}

//日期/转-
function timestampToTime(times) {
  let mdy = []
  mdy = times.split('/')
  let month = parseInt(mdy[1]);
  let day = parseInt(mdy[2]);
  let year = parseInt(mdy[0])
  return year + '-' + month + '-' + day
}

//重置搜索
const refresh = function (){
  keyWord.value = ''
  startTimeForm.value = undefined
  endTimeForm.value = undefined
  state.courseLabel = ''
  state.formatEnd = ''
  state.formatStart = ''
  getActivity(1,10,'','','','')
}

//点击tabs
const changeCategory = function (activeKey){
  getActivity(1,10,keyWord.value,state.formatStart,state.formatEnd,activeKey)
}

const changeNum = function (page){
  getActivity(page,10,keyWord.value,state.formatStart,state.formatEnd,state.courseLabel)
}

const newAudit = ref({})

const startModal = function (item){
  newAudit.value = item
  state.statusValue[0] = newAudit.value.status
  state.isAudit = true
}

const handleOk = function (){
  console.log(state.statusValue[0])
  let newActivity = {
    eventId: newAudit.value.eventId,
    userId: store.state.id,
    status: state.statusValue[0]
  }
  if (newActivity.status == '已通过'){
    newActivity.status = '报名中'
  }
  console.log(newActivity)
  updateActivity(newActivity).then(res =>{
    if (res.data.code == 0) {
      message.success('审核状态成功')
      getActivity(state.current,10,keyWord.value,state.formatStart,state.formatEnd,state.courseLabel)
    }else {
      console.log(res)
      message.error('审核状态失败')
    }
  })
  state.isAudit = false
}
</script>

<style scoped>
.course-name {
  width: 100px;
  margin-left: -2px;
  text-align: center;
  line-height: 32px;
  display: inline-block;
}

.workContent{
  width: 96%;margin: 25px auto 0 auto;
}


.type-name {
  margin: 8px 0 0 14px;
  width: 75px;
  vertical-align: middle;
  display: inline-block;
}


.card-container {
  width: 76%;
  display: inline-block;
}

.show_input_image {
  margin-top: -60px;
  width: 60px;
  height: 60px;
  border: 1px solid #f0f0f0;
}
.input_image {
  position: relative;
  width: 60px;
  height: 60px;
  background-color: blue;
  z-index: 999;
  opacity: 0;
  border-radius: 50%;
}
</style>

<style>
.card-container .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn{
  color: #FFFFFF;
}

.card-container .ant-tabs-card > .ant-tabs-nav .ant-tabs-tab{
  background-color: #FFFFFF;
  border: 0;
}

.card-container  .ant-tabs-card.ant-tabs-top > .ant-tabs-nav .ant-tabs-tab-active {
  background: #1890ff;
  border-radius: 4px;
  margin: 0;
  color: #FFFFFF;
}

.card-container .ant-tabs-card.ant-tabs-top > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab{
  margin: 0;
}

.ant-modal-title{
  font-weight: 600;
}
</style>